<template>
  <div class="home">
    <home-header :category="category" @setCurrentCategory="setCurrentCategory" />

    <div class="home-container" ref="refreshElm">
      <Suspense>
        <template #default>
          <home-swiper />
        </template>
        <template #fallback>
          <div>loading...</div>
        </template>
      </Suspense>

      <home-list :lessonList="lessonList" />
      <div v-if="isLoading" style="margin-top: 170px">正在加载</div>
      <div v-if="hasMore">我是有底线的</div>
    </div>
  </div>
</template>

<script lang="ts">
import { IGlobalState } from '@/store'
import { CATOGORY_TYPES } from '@/typings/home'
import { computed, defineComponent, onMounted, ref } from 'vue'
import { Store, useStore } from 'vuex'
import HomeHeader from './components/home-header.vue'
import HomeList from './components/home-list.vue'
import HomeSwiper from './components/home-swiper.vue'
import * as Types from '@/store/action-types'
import { useLoadMore } from '@/hooks/useLoadMore'
// 专门修改分类使用的
function useCategory(store: Store<IGlobalState>) {
  const category = computed(() => store.state.home.currentCategory) // vuex中的状态
  function setCurrentCategory(category: CATOGORY_TYPES) {
    store.commit(`home/${Types.SET_CATEGORY}`, category)
  }
  return {
    category,
    setCurrentCategory
  }
}

function useLessonLIst(store: Store<IGlobalState>) {
  const lessonList = computed(() => store.state.home.lessons.list)
  onMounted(() => {
    // 初始化加载 mounted生命周期
    if (lessonList.value.length === 0) {
      setTimeout(() => {
        store.dispatch(`home/${Types.SET_LESSON_LIST}`)
      }, 2000)
    }
  })
  return {
    lessonList
  }
}
export default defineComponent({
  components: {
    HomeHeader,
    HomeList,
    HomeSwiper
  },
  setup() {
    // 需要获取vuex中的分类状态 更改状态的功能
    const store = useStore<IGlobalState>()
    // 分类
    const { category, setCurrentCategory } = useCategory(store)
    // 课程获取
    const { lessonList } = useLessonLIst(store)
    // 获取真实dom
    const refreshElm = ref<null | HTMLElement>(null)
    const { isLoading, hasMore } = useLoadMore(refreshElm, store, `home/${Types.SET_LESSON_LIST}`)
    return {
      category,
      setCurrentCategory,
      lessonList,
      refreshElm,
      isLoading,
      hasMore
    }
  }
})
</script>

<style lang="scss">
.home {
  width: 100%;
  height: 100%;
}
.home-container {
  position: absolute;
  top: 65px;
  bottom: 50px;
  width: 100%;
  overflow-y: scroll;
}
</style>
